package com.liyang.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @BelongsProject: cloud-2024
 * @BelongsPackage: com.liyang.lb
 * @Author: liyang
 * @CreateTime: 2023-12-26  14:54
 * @Description: TODO
 * @Version: 1.0
 */
@Component
public class MyLoadBalancer implements LoadBalancer{

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * @description: 自旋
     * @author: liyang
     * @date: 2023/12/26 15:42
     **/
    public final int getAndIncrement()
    {
        int current;
        int next;
        // 自旋  保证  atomicInteger  不会被其他访问请求修改  原始值与期望值一致
        do {
             current = this.atomicInteger.get();
            // 防止越界
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!atomicInteger.compareAndSet(current, next));
        System.out.println("****** 第几次访问，次数next ： " + next +" *******");
        return next;
    }

    /**
     * @description:  负载均衡算法：rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标， 每次服务重启动后rest接口计数从1开始。1
     * @author: liyang
     * @date: 2023/12/26 15:31
     * @param: serviceInstanceList 
     * @return: org.springframework.cloud.client.ServiceInstance
     **/
    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstanceList) {
        int index = getAndIncrement() % serviceInstanceList.size();
        return serviceInstanceList.get(index);
    }
}
